<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var socket;
    if (window.WebSocket) {//支持webSocket编程
        socket = new WebSocket("ws://localhost:8899/hello2");

        //相当于channelReado, ev收到服务器端回送的消息
        socket.onmessage = function (ev) {
            var rt = document.getElementById("responseText");
            rt.value = rt.value + "\n" + ev.data;
        }
        //相当于连接开启(感知到连接开启)
        socket.onopen = function (ev) {
            var rt = document.getElementById("responseText");
            rt.value = "连接开启了.."
        }
        //相当于连接关闭(感知到连接关闭)
        socket.onclose = function (ev) {
            var rt = document.getElementById("responseText");
            rt.value = rt.value + "\n" + "连接关闭了.."
        }
    }

    //发送消息到服务器
    function send(message) {
        if (!window.socket) {//先判断socket是否创建好
            return;
        }
        if (socket.readyState == WebSocket.OPEN) {
            //通过socket发送消息
            socket.send(message)
        } else {
            alert("连接没有开启");
        }
    }
</script>

<form onsubmit="return false">
    <textarea name="message" style="width: 200px;height: 100px;"></textarea>
    <input type="button" value="发送" onclick="send(this.form.message.value)">
    <textarea id="responseText" style="width: 200px;height: 100px;"></textarea>
    <input type="button" value="清空" onclick="document.getElementById('responseText').value='' ">
</form>

</body>
</html>